package com.sunnyweather.android.ui.place

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.sunnyweather.android.MainActivity
import com.sunnyweather.android.R
import com.sunnyweather.android.ui.weather.WeatherActivity
import kotlinx.android.synthetic.main.fragment_place.*

class PlaceFragment : Fragment() {


    val placeViewModel: PlaceViewModel by lazy {
        ViewModelProvider(this)[PlaceViewModel::class.java]
    }

    lateinit var placeAdapter: PlaceAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_place, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)


        if (activity is MainActivity && placeViewModel.isPlaceSaved()) {
            val place = placeViewModel.getSavedPlace()
            val location = place.location
            val intent = Intent(this.context, WeatherActivity::class.java).apply {
                putExtra("location_lng", location.lng)
                putExtra("location_lat", location.lat)
                putExtra("place_name", place.name)
            }
            startActivity(intent)
            activity?.finish()
            return
        }


//泡芙妹妹18+
        val linearLayoutManager = LinearLayoutManager(activity)

        recyclerView.layoutManager = linearLayoutManager

        placeAdapter = PlaceAdapter(this, placeViewModel.placeList)

        recyclerView.adapter = placeAdapter

        searchPlaceEdit.addTextChangedListener { edit ->
            val text = edit.toString()
            if (text.isNotEmpty()) {
                placeViewModel.searchPlaces(text)
            } else {
                bgImageView.visibility = View.GONE
                recyclerView.visibility = View.VISIBLE
                placeViewModel.placeList.clear()
                placeAdapter.notifyDataSetChanged()
            }
        }

        placeViewModel.placeLiveData.observe(viewLifecycleOwner) {
            val placeList = it.getOrNull()
            if (placeList != null) {
                bgImageView.visibility = View.GONE
                recyclerView.visibility = View.VISIBLE
                placeViewModel.placeList.clear()
                placeViewModel.placeList.addAll(placeList)
                placeAdapter.notifyDataSetChanged()
            } else {
                Toast.makeText(this.context, "未能查询出数据", Toast.LENGTH_SHORT).show()
                it.exceptionOrNull()?.printStackTrace()
            }
        }
    }
}